#!/usr/bin/env python3
"""
DSL 语法修复脚本 - 第一阶段
修复语法错误：添加identity字段、简化验证规则、移除无效规则
"""

import os
import re
import yaml
import shutil
from pathlib import Path
from typing import Dict, Any, List

class DSLSyntaxFixer:
    def __init__(self, models_dir: str):
        self.models_dir = Path(models_dir)
        self.processed_files = []
        self.failed_files = []
        
    def fix_all_models(self):
        """修复所有模型文件"""
        print("🚀 开始第一阶段DSL语法修复...")
        
        # 获取所有YAML文件（排除备份文件）
        yaml_files = [f for f in self.models_dir.glob("*.yml") 
                     if not f.name.endswith('.backup')]
        
        for yaml_file in yaml_files:
            try:
                print(f"\n📝 处理文件: {yaml_file.name}")
                self.fix_model_file(yaml_file)
                self.processed_files.append(yaml_file.name)
                print(f"✅ {yaml_file.name} 修复完成")
            except Exception as e:
                print(f"❌ {yaml_file.name} 修复失败: {e}")
                self.failed_files.append(yaml_file.name)
        
        self.print_summary()
    
    def fix_model_file(self, file_path: Path):
        """修复单个模型文件"""
        # 创建备份
        backup_path = file_path.with_suffix('.yml.backup-phase1')
        shutil.copy2(file_path, backup_path)
        
        # 读取文件内容
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 解析YAML
        data = yaml.safe_load(content)
        
        # 修复语法问题
        if 'entities' in data:
            for entity_name, entity_def in data['entities'].items():
                print(f"  🔧 修复实体: {entity_name}")
                self.fix_entity(entity_def, entity_name)
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            yaml.dump(data, f, default_flow_style=False, allow_unicode=True, 
                     sort_keys=False, indent=2)
    
    def fix_entity(self, entity: Dict[str, Any], entity_name: str):
        """修复实体定义"""
        # 1. 添加identity字段（如果缺失）
        if 'identity' not in entity:
            entity['identity'] = 'id'
            print(f"    ➕ 添加identity字段: id")
        
        # 2. 修复属性验证规则
        if 'attributes' in entity:
            for attr_name, attr_def in entity['attributes'].items():
                if 'rules' in attr_def:
                    self.fix_attribute_rules(attr_def['rules'], f"{entity_name}.{attr_name}")
    
    def fix_attribute_rules(self, rules: List[Any], attr_path: str):
        """修复属性验证规则"""
        if not isinstance(rules, list):
            return
        
        new_rules = []
        modified = False
        
        for rule in rules:
            if isinstance(rule, dict):
                # 处理复杂规则
                if 'range' in rule:
                    # 简化range规则为min/max
                    range_def = rule['range']
                    if 'min' in range_def:
                        new_rules.append({'min': range_def['min']})
                    if 'max' in range_def:
                        new_rules.append({'max': range_def['max']})
                    print(f"    🔄 简化range规则: {attr_path}")
                    modified = True
                elif 'length' in rule:
                    # 简化length规则为min/max
                    length_def = rule['length']
                    if 'min' in length_def:
                        new_rules.append({'min': length_def['min']})
                    if 'max' in length_def:
                        new_rules.append({'max': length_def['max']})
                    print(f"    🔄 简化length规则: {attr_path}")
                    modified = True
                elif 'precision' in rule:
                    # 移除precision规则（无效）
                    print(f"    🗑️  移除precision规则: {attr_path}")
                    modified = True
                    continue
                else:
                    new_rules.append(rule)
            elif isinstance(rule, str):
                # 处理简单规则
                if rule in ['primary', 'auto_timestamp']:
                    # 移除无效的简单规则
                    print(f"    🗑️  移除无效规则 '{rule}': {attr_path}")
                    modified = True
                    continue
                else:
                    new_rules.append(rule)
            else:
                new_rules.append(rule)
        
        # 更新规则列表
        if modified:
            rules.clear()
            rules.extend(new_rules)
    
    def print_summary(self):
        """打印修复摘要"""
        print(f"\n{'='*50}")
        print("📊 第一阶段DSL语法修复完成")
        print(f"{'='*50}")
        print(f"✅ 成功处理: {len(self.processed_files)} 个文件")
        for file in self.processed_files:
            print(f"   - {file}")
        
        if self.failed_files:
            print(f"❌ 失败文件: {len(self.failed_files)} 个")
            for file in self.failed_files:
                print(f"   - {file}")
        
        print(f"\n🔧 主要修复内容:")
        print("   - ➕ 添加缺失的identity字段")
        print("   - 🔄 简化range规则为min/max规则")
        print("   - 🔄 简化length规则为min/max规则")
        print("   - 🗑️  移除无效验证规则(precision, primary, auto_timestamp)")
        
        print(f"\n💾 备份文件已创建（.backup-phase1后缀）")
        print(f"📝 建议运行语法检查: npx tsx src/cli/syntax-check.ts models")
        print(f"🔄 如需恢复: find models -name '*.backup-phase1' -exec sh -c 'mv \"$1\" \"${{1%.backup-phase1}}\"' _ {{}} \\;")

def main():
    import sys
    
    if len(sys.argv) != 2:
        print("用法: python3 fix-dsl-syntax-phase1.py <models_directory>")
        sys.exit(1)
    
    models_dir = sys.argv[1]
    if not os.path.exists(models_dir):
        print(f"错误: 目录 {models_dir} 不存在")
        sys.exit(1)
    
    fixer = DSLSyntaxFixer(models_dir)
    fixer.fix_all_models()

if __name__ == "__main__":
    main()